{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n",
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "preprocessor = mz.models.aNMM.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/95 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Dumping model to file cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 2.909 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:03<00:00, 24.49it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 93/93 [00:00<00:00, 109.22it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 93/93 [00:00<00:00, 93229.03it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 93/93 [00:00<00:00, 23257.23it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 93/93 [00:00<00:00, 46536.66it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 95/95 [00:00<00:00, 10554.08it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 93/93 [00:00<00:00, 46614.52it/s]\n",
      "Building Vocabulary from a datapack.: 100%|████████████████████████████████████| 1026/1026 [00:00<00:00, 171107.59it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:00<00:00, 102.10it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 93/93 [00:00<00:00, 98.78it/s] \n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 93/93 [00:00<00:00, 31024.44it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 95/95 [00:00<00:00, 9508.40it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 93/93 [00:00<00:00, 46575.55it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 95/95 [00:00<00:00, 47571.50it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 93/93 [00:00<00:00, 46592.24it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 45/45 [00:00<00:00, 96.41it/s] \n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 85.08it/s] \n",
      "Processing text_right with transform: 100%|██████████████████████████████████████████| 50/50 [00:00<00:00, 4548.25it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 45/45 [00:00<00:00, 9000.65it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 16681.13it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 45/45 [00:00<00:00, 15009.44it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 50/50 [00:00<00:00, 24960.15it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 79.06it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 99.73it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 15047.73it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 29/29 [00:00<00:00, 9663.53it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 14983.22it/s]\n",
      "Processing length_left with len: 100%|███████████████████████████████████████████████| 29/29 [00:00<00:00, 9667.37it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 30/30 [00:00<00:00, 15049.53it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 由于加载glove模型会导致本案例运行速度会变慢，所以不加载glove模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=300)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.aNMM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "aNMM(\n",
      "  (embedding): Embedding(374, 100, padding_idx=0)\n",
      "  (matching): Matching()\n",
      "  (hidden_layers): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=200, out_features=100, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=1, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "  )\n",
      "  (q_attention): Attention(\n",
      "    (linear): Linear(in_features=100, out_features=1, bias=False)\n",
      "  )\n",
      "  (dropout): Dropout(p=0.1, inplace=False)\n",
      "  (out): Linear(in_features=1, out_features=1, bias=True)\n",
      ") 57703\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.aNMM()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "\n",
    "model.params['dropout_rate'] = 0.1\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model, sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5930ac69ee214c54a8d264eba2661d9c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5ac6f21f040c41c0adc38a6aed913972",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8e1bb9e07bbd4cfaa5ece4ddf7652c3d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "233e80957a344156a7061fee5f638590",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "06289c2245ff4e95adfb3c74daf6dc45",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3f4647a3aaa341709a7dbb28ca5b0acc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ce9452bd01814d00a2a86a57bf71f0f6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "188829330ee442098ccade295ed95833",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "02d788167c104fe0b04b3e2852da4526",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0d7ba51a33e14962a75509dec12fdf27",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "33fbdf3c0ec941bab203e0ab2cfdda79",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-11 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "86373b93c4c547228deb6521b227d0ec",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-12 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1b84d4afbaf84af9b541e3b351e7ecce",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-13 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5262b17b58724fe29b310cfb06e93c1a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-14 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c7ef3c7f7d114feb96f0e1d2c6ccca28",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-15 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1613 - normalized_discounted_cumulative_gain@5(0.0): 0.1613 - mean_average_precision(0.0): 0.1613\n",
      "\n",
      "Cost time: 7.518690347671509s\n"
     ]
    }
   ],
   "source": [
    "optimizer = torch.optim.Adam(model.parameters(), lr = 3e-4)\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=15\n",
    ")\n",
    "\n",
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1125"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
